package com.example.demo01.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.demo01.R;
import com.example.demo01.entity.UserDemo;

import java.util.ArrayList;
import java.util.List;

public class SpinnerDemoAdapter extends BaseAdapter {

    Context context;
    List<UserDemo> data = new ArrayList<UserDemo>();

    public SpinnerDemoAdapter(Context context, List<UserDemo> data) {
        this.context = context;
        this.data = data;
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public UserDemo getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return data.get(position).getId();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // ViewHolder模式优化（避免重复查找视图）
        ViewHolder holder;

        if (convertView == null) {
            LayoutInflater Inflater = LayoutInflater.from(context);
            convertView = Inflater.inflate(R.layout.item_spinner, parent, false); // 根据布局文件创建视图

            holder = new ViewHolder();
            holder.textView = convertView.findViewById(R.id.textView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.textView.setText(getItem(position).getName());

        return convertView;
    }


    // ViewHolder静态内部类（用于缓存视图组件）
    static class ViewHolder {
        TextView textView;
    }
}

